package tessk.jwt;

import java.security.Key;
import java.util.Date;

import javax.crypto.spec.SecretKeySpec;
import javax.xml.bind.DatatypeConverter;

import io.jsonwebtoken.Claims;
import io.jsonwebtoken.JwtBuilder;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;

public class JwtHelper {

	public static Claims parestJWT(String jsonWebToken,String base64Security){
		try{
			Claims claims = Jwts.parser()
					.setSigningKey(DatatypeConverter.parseBase64Binary(base64Security))
					.parseClaimsJws(jsonWebToken).getBody();
			return claims;
		}catch(Exception ex){
			return null;
		}
	}
	
	public static String createJWT(String name,String userId,String audience,long TTL,String base64Security){
		SignatureAlgorithm  signatureAlgorithm =SignatureAlgorithm.HS256;
		long nowMillis =System.currentTimeMillis();
		Date now = new Date(nowMillis);
		
		byte[] apiKeySecretBytes = DatatypeConverter.parseBase64Binary(base64Security);  
        Key signingKey = new SecretKeySpec(apiKeySecretBytes, signatureAlgorithm.getJcaName());  
        
        JwtBuilder builder = Jwts.builder().setHeaderParam("typ", "JWT")
        		.claim("username", name)
        		.claim("userid", userId)
        		.setAudience(audience)
        		.signWith(signatureAlgorithm, signingKey);
        
        if(TTL >=0){
        	long expMillis =nowMillis +TTL;
        	Date exp = new Date(expMillis);
        	builder.setExpiration(exp).setNotBefore(now);
        }
        
        return builder.compact();
	}
}
